import React, { Component } from 'react'
import Home from './acclist/Home'
import Add from './acclist/Add'
import { Switch, Route, Redirect } from 'react-router-dom/cjs/react-router-dom.min'
import Ctx from './acclist/store/Ctx'

export default class App extends Component {

  state = {
    //数据
    list: [ //type=0是支出 =1收入
      { id: 1, title: '吃喝', price: 15, sed: false, type: 0, bz: '大盘鸡' },
      { id: 2, title: '兼职', price: 1000, sed: true, type: 1, bz: '做了一个小程序' },
    ]
  }

  //sed状态切换
  changeSed = (id) => {
    let newlist = [...this.state.list]
    newlist.forEach(item => {
      if (item.id == id) {
        return item.sed = !item.sed
      }
    })
    this.setState({ list: newlist })
  }

  //删除选中的数据
  changedelAll = () => {
    let newlist = this.state.list.filter(item => {
      return !item.sed
    })
    this.setState({ list: newlist })
  }
  //单个删除
  changedelOne = (id) => {
    let newlist = this.state.list.filter(item => {
      return item.id !== id
    })
    this.setState({ list: newlist })
  }
  //总收入
  changeSr = () => {
    return this.state.list.reduce((p, n) => {
      if (n.type == 1) {
        return p + n.price * 1
      }
      return p
    }, 0)
  }
  //总支出
  changeZc = () => {
    return this.state.list.reduce((p, n) => {
      if (n.type == 0) {
        return p + n.price * 1
      }
      return p
    }, 0)
  }
  //反选 参数c是布尔值
  changeSetSed = (c) => {
    let newlist = [...this.state.list]
    newlist.forEach(item => {
      item.sed = c
    })
    this.setState({ list: newlist })
  }
  //添加方法
  add = (obj) => {
    this.setState({ list: [...this.state.list, obj] })
  }

  render() {
    return (<Ctx.Provider value={{
      ...this.state,//浅拷贝数据
      changeSed: this.changeSed,//状态切换
      changedelAll: this.changedelAll,//批量删除
      changedelOne: this.changedelOne,//单个删除
      changeSr: this.changeSr,//总收入
      changeZc: this.changeZc,//总支出
      changeSetSed: this.changeSetSed,//反选
      add: this.add//添加
    }}>
      <div>
        <Switch>
          <Route path='/home' component={Home} />
          <Route path='/add' component={Add} />
          <Redirect from='/' to='/home' />
        </Switch>
      </div>
    </Ctx.Provider>

    )
  }
}
